import Vue from "vue";
import axios from "axios";

//import { baseHost } from "./config";
let domain = "http://192.168.110.23:8089/";

const isProduction = process.env.NODE_ENV === "production";
const api = axios.create();
api.defaults.baseURL = domain;
api.defaults.timeout = isProduction ? 10000 : 3000;
api.defaults.headers.post["Content-Type"] = "application/json";
api.defaults.headers.post["token"] = localStorage.getItem("token") || "";
api.interceptors.request.use(
  function(config) {
    console.log(config);
    return config;
  },
  function(error) {
    // 对请求错误
    return Promise.reject(error);
  }
);
api.interceptors.response.use(
  function(response) {
    return response;
  },
  function(error) {
    return Promise.reject(error);
  }
);

Vue.prototype.$api = api;

Vue.$defaultFontSize = Vue.prototype.$defaultFontSize = (num) => {
  // eslint-disable-next-line no-redeclare
  num = num || 16;
  let iWidth = (document.documentElement || document.body).clientWidth,
    iHeight = (document.documentElement || document.body).clientHeight,
    fontSize =
      (window.orientation &&
        (window.orientation === 90 || window.orientation === -90)) ||
      iHeight < iWidth
        ? iHeight / num
        : iWidth / num;
  window.baseFontSize = fontSize;
  document.getElementsByTagName("html")[0].style.fontSize =
    fontSize.toFixed(2) + "px";
  return fontSize;
};

Vue.prototype.$uploaderImg = function(file) {
  //file为 你读取成功的回调文件信息
  //new 一个FormData格式的参数
  let params = new FormData();
  params.append("file", file);
  let config = {
    headers: {
      //添加请求头
      "Content-Type": "multipart/form-data",
    },
  };
  return new Promise((resolve, reject) => {
    //把 uploadUrl 换成自己的 上传路径
    api
      .post("/uploader", params, config)
      .then((res) => {
        if (res && res.data && res.data.status === 1) {
          //如果为真 resolve出去
          resolve(res.data);
        } else {
          //否则 Toast 提示
          reject(res.data);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
};

let formatDate = (Vue.prototype.formatDate = (date, fmt) => {
  date = new Date(date);
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  let o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
  };
  for (let k in o) {
    let str = o[k] + "";
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? str : padLeftZero(str)
      );
    }
  }
  return fmt;
});

Vue.prototype.getDateDiff = (dateTimeStamp, v, $t) => {
  var minute = 1000 * 60;
  var hour = minute * 60;
  var day = hour * 24;
  var halfamonth = day * 15;
  var month = day * 30;

  var now = new Date().getTime();
  var diffValue = now - dateTimeStamp;

  var monthC = diffValue / month;
  var weekC = diffValue / (7 * day);
  var dayC = diffValue / day;
  var hourC = diffValue / hour;
  var minC = diffValue / minute;
  let result = "";
  if (hourC >= 12) {
    result = formatDate(dateTimeStamp, v);
  } else if (hourC >= 1) {
    result = parseInt(hourC) + "个小时前";
  } else if (minC >= 1) {
    result = parseInt(minC) + "分钟前";
  } else result = "刚刚";
  return result;
};

function padLeftZero(str) {
  return ("00" + str).substr(str.length);
}

Vue.$Cookie = (key) => {
  let arr,
    reg = new RegExp("(^| )" + key + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) return JSON.parse(unescape(arr[2]));
  else return null;
};

Vue.prototype.$iphoneBool = () => {
  let device = "";
  if (
    /iphone/gi.test(window.navigator.userAgent) &&
    window.devicePixelRatio &&
    window.devicePixelRatio === 3 &&
    window.screen.width === 375 &&
    window.screen.height === 812
  ) {
    device = "iphoneX";
  } else if (
    /iphone/gi.test(window.navigator.userAgent) &&
    window.devicePixelRatio &&
    window.devicePixelRatio === 3 &&
    window.screen.width === 414 &&
    window.screen.height === 896
  ) {
    device = "iphoneXSMax";
  } else if (
    /iphone/gi.test(window.navigator.userAgent) &&
    window.devicePixelRatio &&
    window.devicePixelRatio === 2 &&
    window.screen.width === 414 &&
    window.screen.height === 896
  ) {
    device = "iphoneXR";
  }
  return device;
};
